#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/2/13
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R39_EC_EnterpriseEnforcementAdministrativePenaltyCheck_XD
# @Software  :PyCharm

'''eof
name:申请企业企业强制执行、行政处罚校验
code:R39_EC_EnterpriseEnforcementAdministrativePenaltyCheck_XD
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import pandas as pd
import sys
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')


last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).date()\
                    for i in range(6)]

def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo

null_type_list = ['', ' ', None, 'nulll', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = EC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['ReportNo'] in null_type_list:
                return [{}]
            # 存在空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d')
        except:
            return_data = None

    return return_data



def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None


# 获取 上次申请时间
def get_relative_date():
    relative_date = ratingRequest.get('relativeDate')
    return formatDate(relative_date)



def discriminantFunc(dataTime, money):
    """
    执行表中的规则判断
    :param data: 日期
    :param money: 金额
    :return:
    """

    Factor = 1
    CrrDate = datetime.datetime.now().date()
    if dataTime < last_year_list[-1]:
        Factor = 1

    if dataTime < last_year_list[3] and \
            dataTime >= last_year_list[-1]:
        if money <= 25000:
            Factor = 1
        else:
            Factor = 0

    if dataTime < last_year_list[2] and \
            dataTime >= last_year_list[3]:
        if money <= 15000:
            Factor = 1
        else:
            Factor = 0

    if dataTime <= last_year_list[0] and dataTime >= last_year_list[2]:
        if money < 6000:
            Factor = 1
        else:
            Factor = 0
    if dataTime > CrrDate:
        Factor = 0

    return Factor

def enterpriseEnforcementAdministrativePenaltyCheck():
    """
    "【计算逻辑】
    1）从企业征信接口强制执行记录（ECRForceExecution）中取立案日期（Caseregistrationdate）、
    已执行标的金额（元）（Executedobjectamount）、案号（Casenumber）字段进行矩阵判断（原走人工判断在此作拒绝处理）；
    2）从行政处罚记录（ECRAdminPunishment）中取处罚金额（Punishmentamount）、
    处罚日期（Punishmentdate）进行矩阵判断（原走人工判断在此作拒绝处理）
    以下是在执行表中的规则判断：
    1. 若立案时间在5年外，则Factor=1；
    2. 若执行标的字段内容为空或0，或者立案时间存在除正常格式“0000-00-00”之外的其他异常情况，或者立案时间、案号字段内容为空时，Factor=2；
    3. 若立案时间大于当前时间，Factor=2；
    4. 若立案时间在2年内（含），执行标的在6000元内，则Factor=1，执行标的大于等于6000元，则Factor返回0；
    5. 若立案时间在2-3年内（含），执行标的在15000元内（含），则Factor=1，执行标的大于15000元，则Factor=0；
    6. 若立案时间在3-5年内（含），执行标的在25000元内（含），则Factor=1，执行标的大于25000元，则Factor=0；
    注：0=拒绝，1=通过，2=转人工。
    【指标值】
    1、当表都为[]时，则通过；"

    :return:
    """

    Null = ['', ' ', None, 'nulll', 'Null', 'NULL', '/', '-', '--']
    ECRForceExecution = getTable('ECRForceExecution')
    ECRAdminPunishment = getTable("ECRAdminPunishment")
    relativeDate = get_relative_date()
    if relativeDate is None:
        raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
    # 走人工 也是 拒绝
    if ECRForceExecution == [{}]:
        Factor1 = 1
    elif ECRForceExecution is None:
        Factor1 = 0
    else:
        FactorList = []
        # 强制执行记录
        for i in range(len(ECRForceExecution)):
            # 立案日期
            Caseregistrationdate = ECRForceExecution[i].get("Caseregistrationdate")
            # 执行金额
            Executedobjectamount = ECRForceExecution[i].get("Executedobjectamount")
            # 案号
            Casenumber = ECRForceExecution[i].get('Casenumber')

            if Caseregistrationdate in Null or Executedobjectamount in Null or Casenumber in Null:
                FactorList.append(None)
            else:

                if convertDataType(Caseregistrationdate, 'date_time') is not None:
                    # 将立案时间限定在 上一次申请时间之间
                    if convertDataType(Caseregistrationdate, 'date_time') > relativeDate:
                        Caseregistrationdate = convertDataType(Caseregistrationdate, 'date_time').date()
                        Executedobjectamount = convertDataType(Executedobjectamount, 'float')
                        # print Caseregistrationdate, Executedobjectamount, discriminantFunc(dataTime=Caseregistrationdate, money=Executedobjectamount)
                        FactorList.append(discriminantFunc(dataTime=Caseregistrationdate, money=Executedobjectamount))
                else:
                    FactorList.append(None)
        if None in FactorList or 0 in FactorList:
            Factor1 = 0
        else:
            Factor1 = 1

    if ECRAdminPunishment is None:
        Factor2 = 0
    elif ECRAdminPunishment == [{}]:
        Factor2 = 1
    else:
        # 行政处罚记录
        FactorList = []
        for i in range(len(ECRAdminPunishment)):
            # 处罚日期
            Punishmentdate = ECRAdminPunishment[i].get("Punishmentdate")
            # 处罚金额
            Punishmentamount = ECRAdminPunishment[i].get("Punishmentamount")
            # 案号
            Punishmentdocumentnumber = ECRAdminPunishment[i].get('Punishmentdocumentnumber')

            if Punishmentdate in Null or Punishmentamount in Null or Punishmentdocumentnumber in Null:
                FactorList.append(None)
            else:
                if convertDataType(Punishmentdate, 'date_time') is not None:
                    # 将处罚时间限定在 上一次申请时间之间
                    if convertDataType(Punishmentdate, 'date_time') > relativeDate:
                        Punishmentdate = convertDataType(Punishmentdate, 'date_time').date()
                        Punishmentamount = convertDataType(Punishmentamount, 'float')
                        FactorList.append(discriminantFunc(dataTime=Punishmentdate, money=Punishmentamount))
                else:
                    FactorList.append(None)
        if 0 in FactorList or None in FactorList:
            Factor2 = 0
        else:
            Factor2 = 1

    if Factor1 == 0 or Factor2 == 0:
        return 0
    else:
        return 1



result = enterpriseEnforcementAdministrativePenaltyCheck()

if __name__ == '__main__':

    import json
    ratingRequest = {"legalPerson": u"朱为广", "legalPersonIdCard": "510102196706108511", "creditCode": "123456",
                     "regNumber": "12345", "relativeDate":u'2016/08/09'}
    file_obj = open(r'E:\\HQDIndicators\\testFiles\\EC_DSJ.json', 'r')
    content = file_obj.read()
    EC_DSJ = json.loads(content, strict=False).get('EC_DSJ')
    aa = enterpriseEnforcementAdministrativePenaltyCheck()
    print aa